import { _decorator, Button, Component, EventTouch, instantiate, Label, Node, Prefab, resources, Sprite, SystemEvent, tween, Tween, v3 } from 'cc';
import BaseView from '../../../platform/ui/BaseView';
import { Game_2048_MergeDirection, Game_Level_Names, Game_Levels, Game_Status, Menu_Btns, ViewLayerDefine } from '../../common/enums';
import { ResManager } from '../../../platform/resources/ResMgr';
import { bind, uiview } from '../../../platform/ui/UIDecorator';
import { watch } from '@vue/reactivity';
import { LogMgr } from '../../../platform/log/LogMgr';
import { TbRoot } from '../../../platform/excel_table/TbRoot';
import { Tb_GameList, Tb_GameListContainer } from '../../tb/Tb_GameList';
import UIMgr from '../../../platform/ui/UIMgr';
import { Game2048Model } from './Game2048Model';
import { Game2048Ctl } from './Game2048Ctl';
import { game2048_cellColors } from '../../static_config';
import { PlayerData } from '../../data/player/PlayerData';
const { ccclass, property } = _decorator;





@uiview({
    prefabPath:"prefab/ui/2048/Game2048PlayView",
    layer:ViewLayerDefine.Pop,
    dataModel:Game2048Model,
    controller:Game2048Ctl,
    single:true
})
@ccclass('Game2048PlayView')
export class Game2048PlayView extends BaseView<Game2048Model,Game2048Ctl> {
    //#region 节点绑定
    @bind(Label)
    title:Label = null

    @bind(Node)
    back:Node = null
    @bind(Node)
    rule:Node = null
    @bind(Node)
    rule_tips:Node = null
    @bind(Node)
    share:Node = null
    @bind(Node)
    volumn:Node = null

    @bind(Node)
    endPanel:Node = null
    @bind(Node)
    stastics:Node = null
    @bind(Node)
    end_sure:Node = null

    @bind(Label)
    nowPoint:Label = null
    @bind(Label)
    maxPoint:Label = null

    @bind(Node)
    board:Node = null
    @bind(Node)
    cells_4:Node = null
    @bind(Node)
    cells_5:Node = null

    @bind(Button)
    restart:Button = null
    //#endregion
    cfg:Tb_GameList = null
    level:number = 0
    touchStartPos : { x:number, y: number } |null= null;
    readonly mergeMinDistance: number = 50;//滑动达到这个距离才会触发合并
    cellTween:Tween<Node> = null

    protected init(): void {

        //得分

        //按钮
        this.initBtns()
        this.initLevels()

    }
    initLevels() {

    }
    initBtns() {
        this.back.on(Button.EventType.CLICK, this.onBackClick, this)
        this.volumn.on(Button.EventType.CLICK, this.onVolumnClick, this)
        this.share.on(Button.EventType.CLICK, this.onShareClick, this)
        this.rule.on(Button.EventType.CLICK, this.onRuleClick, this)
        this.restart.node.on(Button.EventType.CLICK, this.onRestartClick, this)
        this.rule_tips.on(Button.EventType.CLICK, this.onRuleTipsClick, this)

        this.board.on(SystemEvent.EventType.TOUCH_START, this.onTouchStart, this);
        this.board.on(SystemEvent.EventType.TOUCH_END, this.onTouchEnd, this);
        this.board.on(SystemEvent.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
        this.end_sure.on(Button.EventType.CLICK, this.onEndSureClick, this);
    }
    addListener(target:Node, eventType: SystemEvent.EventType, callback: Function, callObj:any) {


    }
    protected show(...args: any[]): void {
        this.cfg = this.showArgs[0]
        this.level = this.showArgs[1]
        //标题
        this.title.string = this.cfg.name+"-"+Game_Level_Names[this.level]
        this.touchStartPos = null
        //重新初始化游戏？
        //TODO 先从本地读取数据
        this.loadLocalData()

        this.checkGameStatus(true)
        this.refreshBoard(null)
        this.updateShowData()
    }
    updateShowData() {
        this.nowPoint.string = `${this.dataModel.nowPoint}`
    }
    protected getModelKey(): string {
        return this.cfg.name+"_"+this.level
    }
    loadLocalData() {
        let key = this.getModelKey()
        ezgame.info("modelkey:"+key)
        let levelLocalDataStr = localStorage.getItem(key)
        if(levelLocalDataStr){
            this.dataModel.resetData(JSON.parse(levelLocalDataStr))
        }
        this.dataModel.level = this.level
    }

    protected close() {
        // this.back.off(Button.EventType.CLICK, this.onBackClick, this)
        //数据存盘
        localStorage.setItem(this.getModelKey(),JSON.stringify(this.dataModel))
    }
    checkGameStatus(showCheck:boolean) {
        let status = this.dataModel.gameState
        if(status==Game_Status.Uninit || status==Game_Status.End){
            if(status==Game_Status.End && !showCheck){
                this.endPanel.active = true
                //统计面板显示数据
                this.showStasticsData()
            
            }
            //初始化话游戏
            this.controller.initGame()
            this.controller.startGame()
            localStorage.removeItem(this.getModelKey())
            this.refreshBoard(null)
            return
        }
        if(status==Game_Status.Init){
            //初始化话游戏
            this.controller.startGame()
            return
        } 
        if(status==Game_Status.Pause){
            //弹窗提示游戏暂停中，让玩家点击继续或重新开始
            return
        }  
    }
    showStasticsData() {
        let children = this.stastics.children
        let numberTimes = this.dataModel.numberTimes
        let base = 4;
        for (let index = 0; index < children.length; index++) {
            const element = children[index];

            let num = 0
            if(index<4){
                num = this.dataModel.directionTimes.get(index)
            }else{
                num = numberTimes.get(base)
                base*=2
            }
            if(!num){
                num=0
            }
            this.setStasticNum(element,num)
        }
    }
    setStasticNum(stasticItem:Node,num:number) {
        let numLableNode =stasticItem.getChildByName("num")
        numLableNode.getComponent(Label).string = `${num}`
    }

    //#region 棋盘触摸事件

    onTouchStart(event: EventTouch) {
        if(this.dataModel.gameState != Game_Status.Playing) return;
        if(this.touchStartPos) {
            //TODO tips组件通用化
            // UIMgr.ins.tips("操作太快了，请稍后再试试");
            return
        }
        const location = event.getLocation();
        this.touchStartPos = { x: location.x, y: location.y };
    }
    onTouchEnd(event: EventTouch) {
        if(this.dataModel.gameState != Game_Status.Playing) return;
        if (!this.touchStartPos) return;

        const location = event.getLocation();
        const deltaX = location.x - this.touchStartPos.x;
        const deltaY = location.y - this.touchStartPos.y;

        // 记录当前的位置
       
        // 判断是水平还是垂直滑动
        let direction = null
        if (Math.abs(deltaX) > Math.abs(deltaY)) {
            // 水平滑动
            if (Math.abs(deltaX) > this.mergeMinDistance) {
                if (deltaX > 0) {
                    direction = Game_2048_MergeDirection.right
                } else {
                    direction = Game_2048_MergeDirection.Left
                }
            }
        } else {
            // 垂直滑动
            if (Math.abs(deltaY) > this.mergeMinDistance) {
                if (deltaY > 0) {
                    direction = Game_2048_MergeDirection.Up
                } else {
                    direction = Game_2048_MergeDirection.Down
                }
            }
        }
        if(direction!=null){
            let pos = this.controller.merge(direction)
            if(this.dataModel.passed){
                PlayerData.ins.game2048.levelInfos[this.level]
            }
            this.checkGameStatus(false)
            this.refreshBoard(pos);
            this.updateShowData()
        }
        // 在这里做动画
        // this.playMoveAnimation();

        this.touchStartPos = null;
    }

    onEndSureClick() {
        this.endPanel.active = false;
    }

    getNowLevelCells(){
        if(this.level===Game_Levels.Simple){
            this.cells_5.active = false
            this.cells_4.active = true
            return this.cells_4
        }
        if(this.level===Game_Levels.Normal){
            this.cells_5.active = true
            this.cells_4.active = false
            return this.cells_5
        }
    }
    refreshBoard(pos:number[]) {
        let children = this.getNowLevelCells().children
        let data = this.dataModel.boardData
        let row = this.dataModel.row
        let col = this.dataModel.col

        for (let i = 0; i < row; i++) {
            for (let j = 0; j <col; j++) {
                let element = data[i][j];
                let cell = children[i*row+j]
                let labelNode = cell.children[0]
                if(element == 0){
                    labelNode.active = false
                    cell.getComponent(Sprite).color =game2048_cellColors[0]
                }else{
                    labelNode.getComponent(Label).string = element.toString()
                    labelNode.active = true
                    cell.getComponent(Sprite).color = game2048_cellColors[element]
                    if(pos && pos[0] == i && pos[1] == j){
                        this.getCellTween(cell)
                        this.cellTween.start()
                    }
                }
            }
        }
    }
    getCellTween(cell:Node){
        if(this.cellTween){
            this.cellTween.stop()
            let targe = this.cellTween.getTarget()
            if(targe){
                targe.setScale(1,1,1)
            }
        }
        this.cellTween = tween(cell)
        .to(0.1,{scale:v3(1.2,1.2,1)})
        .to(0.1,{scale:v3(1,1,1)})
        .union()
        .repeat(2)
    }
    //#region

    onBackClick(){
                //判断游戏是否进行中，二次确认退出
        // UIMgr.ins.closeUI(Game2048PlayView)
        //TODO 记录状态信息到本地
        ezgame.ui.closeUI(this)
    }
    onVolumnClick(){
        LogMgr.info("音量开关")
    }
    onShareClick(){
        LogMgr.info("点击分享")
    }
    onRuleClick(){
        LogMgr.info("点击规则按钮")
        this.rule_tips.active = true
    }
    onRestartClick(){
        LogMgr.info("点击重新开始按钮")
        this.controller.endGame()
        this.checkGameStatus(false)
    }
    onRuleTipsClick(){
        this.rule_tips.active = false
    }
}



